package com.norma.netty.study.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author zhangchaofeng
 * @date 2020/10/3
 * @description netty客户端
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        //创建客户端时间循环组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象，注意客户端创建的是不是serverBootstrap而是bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(group).channel(NioSocketChannel.class)//设置客户端的通道实现类
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());//加入自己的处理器
                        }
                    });
            System.out.println("client is ok ~");
            //启动客户端连接服务端
            //channelFuture 涉及到netty的异步模型 sync设置成阻塞
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8888).sync();
            //给关闭通道添加监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            //发生异常关闭通道
            group.shutdownGracefully();
        }
    }
}
